package itsen.com.bduidemo.lib.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 *  自定义viewGrouop所涉及到的测量和onLayout布局问题
 *  子view的layout方法来确定自身在父view中的位置
 *  重点：计算好子view 的位置并调用view.layout
 *
 *  ViewGroup 首先调用 layout() 来确定自己本身在其父 View 中的位置（他的父view调用的），
 *  然后调用 onLayout() 确定每个子 View 的位置，
 *  每个子 View 又会调用 View 的 layout() 方法来确定自己在 ViewGroup 的位置。
 */

public class FlowLayout extends ViewGroup {
    /**
     * 用来保存每行views的列表
     */
    private List<List<View>> mViewLinesList = new ArrayList<>();
    /**
     * 用来保存行高的列表
     */
    private List<Integer> mLineHeights = new ArrayList<>();

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获取父容器为FlowLayout设置的测量模式和大小
        int iWidthMode = MeasureSpec.getMode(widthMeasureSpec);//获取模式
        int iHeightMode = MeasureSpec.getMode(heightMeasureSpec);//获取模式
        int iWidthSpecSize = MeasureSpec.getSize(widthMeasureSpec);//建议的宽度
        int iHeightSpecSize = MeasureSpec.getSize(heightMeasureSpec);//建议的高度

        int measuredWith = 0;//最终测量的宽度
        int measuredHeight = 0;//最终测量的高度
        int iCurLineW = 0;//当前行的宽度
        int iCurLineH = 0;//当前行的高度
        if (iWidthMode == MeasureSpec.EXACTLY && iHeightMode == MeasureSpec.EXACTLY) {
            measuredWith = iWidthSpecSize;
            measuredHeight = iHeightSpecSize;
        } else {
            int iChildWidth;
            int iChildHeight;
            int childCount = getChildCount();
            List<View> viewList = new ArrayList<>();
            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                MarginLayoutParams layoutParams = (MarginLayoutParams) childView.getLayoutParams();
                iChildWidth = childView.getMeasuredWidth() + layoutParams.leftMargin +
                        layoutParams.rightMargin;
                iChildHeight = childView.getMeasuredHeight() + layoutParams.topMargin +
                        layoutParams.bottomMargin;
                //当前行的宽度加上下一个子view的宽度大于建议的宽度那么就要换行，否则走else的代码
                if (iCurLineW + iChildWidth > iWidthSpecSize) {
                    //換行
                    /**1、记录当前行的信息***/

                    //1、记录当前行的最大宽度（保证measuredWidth始终是最大的值，这样这样才能显示最大行的所有view）
                    measuredWith = Math.max(measuredWith, iCurLineW);
                    //2、高度累加
                    measuredHeight += iCurLineH;
                    //3、将当前行的viewList添加至总的mViewsList，将行高添加至总的行高List
                    mViewLinesList.add(viewList);
                    mLineHeights.add(iCurLineH);

                    /**2、记录新一行的信息***/

                    //1、重新赋值新一行的宽、高
                    iCurLineW = iChildWidth;
                    iCurLineH = iChildHeight;

                    // 2、新建一行的viewlist，添加新一行的view
                    viewList = new ArrayList<View>();
                    viewList.add(childView);

                } else {
                    //不換行
                    // 记录某行内的消息
                    //1、行内宽度的叠加、高度比较
                    iCurLineW += iChildWidth;
                    iCurLineH = Math.max(iCurLineH, iChildHeight);

                    // 2、添加至当前行的viewList中
                    viewList.add(childView);
                }

                /*****3、如果子view是最後一個的話需要單獨處理**********/
                if (i == childCount - 1) {
                    //1、记录当前行的最大宽度，高度累加
                    measuredWith = Math.max(measuredWith, iCurLineW);
                    measuredHeight += iCurLineH;

                    //2、将当前行的viewList添加至总的mViewsList，将行高添加至总的行高List
                    mViewLinesList.add(viewList);
                    mLineHeights.add(iCurLineH);
                }
            }
        }
        // 最终目的
        setMeasuredDimension(measuredWith, measuredHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int left, top, right, bottom;
        int curTop = 0;
        int curLeft = 0;
        int lineCount = mViewLinesList.size();
        for (int i = 0; i < lineCount; i++) {
            List<View> viewList = mViewLinesList.get(i);
            int lineViewSize = viewList.size();
            for (int j = 0; j < lineViewSize; j++) {
                View childView = viewList.get(j);
                MarginLayoutParams layoutParams = (MarginLayoutParams) childView.getLayoutParams();

                left = curLeft + layoutParams.leftMargin;
                top = curTop + layoutParams.topMargin;
                right = left + childView.getMeasuredWidth();
                bottom = top + childView.getMeasuredHeight();
                //确定子view的位置
                childView.layout(left, top, right, bottom);
                curLeft += childView.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            }
            curLeft = 0;
            curTop += mLineHeights.get(i);
        }
        //測量過程會有多次，所以這裏要進行清理
        mViewLinesList.clear();
        mLineHeights.clear();
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int index);
    }

    public void setOnItemClickListener(final OnItemClickListener listener) {

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            final int finalI = i;
            childView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    listener.onItemClick(v, finalI);
                }
            });
        }
    }
}
